package com.shuda.business.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuda.business.user.entity.UserEntity;
import com.shuda.business.user.entity.UserRoleEntity;
import com.shuda.business.user.mapper.UserMapper;
import com.shuda.business.user.mapper.UserRoleMapper;
import com.shuda.business.user.service.UserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色关联服务实现类
 */
@Service
@RequiredArgsConstructor
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRoleEntity> implements UserRoleService {

    private final UserMapper userMapper;

    @Override
    public List<Long> getRoleIdsByUserId(Long userId) {
        LambdaQueryWrapper<UserRoleEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRoleEntity::getUserId, userId);
        List<UserRoleEntity> userRoles = list(wrapper);
        return userRoles.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toList());
    }

    @Override
    public void updateUserRoles(Long userId, List<Long> roleIds) {
        // 删除原有角色关联
        LambdaQueryWrapper<UserRoleEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRoleEntity::getUserId, userId);
        remove(wrapper);

        // 添加新的角色关联
        if (roleIds != null && !roleIds.isEmpty()) {
            List<UserRoleEntity> userRoles = roleIds.stream()
                    .map(roleId -> {
                        UserRoleEntity userRole = new UserRoleEntity();
                        userRole.setUserId(userId);
                        userRole.setRoleId(roleId);
                        return userRole;
                    })
                    .collect(Collectors.toList());
            saveBatch(userRoles);
        }
    }

    @Override
    public List<UserEntity> getUsersByRoleId(Long roleId) {
        LambdaQueryWrapper<UserRoleEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRoleEntity::getRoleId, roleId);
        List<UserRoleEntity> userRoles = list(wrapper);
        
        if (userRoles.isEmpty()) {
            return List.of();
        }
        
        List<Long> userIds = userRoles.stream().map(UserRoleEntity::getUserId).collect(Collectors.toList());
        return userMapper.selectBatchIds(userIds);
    }
}